import store from '@/store';
import $http from '@/config/requestConfig'
import base from '@/config/baseUrl';
// #ifdef H5
import {
	h5Login
} from '@/config/html5Utils';
// #endif
let code = "";
let loginStart = true;
let userInfo = {
	token: ""
};
let lastPageUrl = "";
// 微信小程序点击学生登录
async function onLogin(auto=true, type = "judge", callback) {
	//判断登录状态
	if (loginStart) {
		lastPageUrl = "";
		loginStart = false;
		const _this = this;
		let platform;
		// #ifdef MP-WEIXIN
		platform = 'weixin';
		// #endif
		//弹窗获取信息
		await getUserProfile(platform,callback,type)	
	}
}

//获取用户授权弹窗
function getUserProfile(platform,type,callback){
	return  new Promise((resolve, reject)=>{
		// // 弹窗授权获取用户信息
		uni.getUserProfile({
			desc: '微信登陆',
			provider: platform,
			success: async function(infoRes) {
				console.log('获取用户信息', infoRes)
				 uni.removeStorageSync('userInfo');
				 store.commit('setUserInfo', {});
				await login(platform)//获取code
				getUserInfo(infoRes, "", callback,code)//登陆
				resolve()
			},
			fail(err) {
				if (type != "try") {
					console.log('获取用户信息失败', err)
					// store.commit('setLoginPopupShow', true);
					// Object.defineProperty(userInfo, "token", {
					// 	get: function(val) {
					// 		return {};
					// 	},
					// 	set: function(newVal) {
					// 		callback && callback();
					// 	}
					// });
					setTimeout(() => {
						loginStart = true;
					}, 1000);
				} else {
					loginStart = true;
				}
			}
		});
	})
}

function login(platform){
	return new Promise((resolve, reject)=>{
	  uni.login({
	  	provider: platform,
	  	success: function(loginRes) {
	  		if (loginRes.errMsg == 'login:ok') {
	  			code = loginRes.code;
				resolve(code)
	  		}
	  	}
	  });
	});
}


//登陆微信小程序更新用户信息
function getUserInfo(info, type, callback,code) {
	let httpData = {
		code: code, //小程序code
		// eduWxAccount: info.eduWxAccount, //用户信息
		eduWxAccount: info.userInfo, //用户信息
		// iv: info.iv, //小程序加密算法的初始向量
		// encryptedData: info.encryptedData //包括敏感数据在内的完整用户信息的加密数据
	};
	
	// store.state.chatScenesInfo里面是小程序二维码附带的信息
	if (store.state.chatScenesInfo.recommendCode) {
		// 推荐码
		httpData.recommendUid = store.state.chatScenesInfo.recommendCode;
	}
	$http.post('/wx/auth/login_by_weixin', httpData).then(res => {
		loginStart = true;
		console.log('微信登陆', JSON.stringify(res))
		if(res.code === 200) {
			let userData = {
				avatarUrl: res.data.eduWxAccount.avatarUrl,
				token: res.data.token,
				userId: res.data.eduWxAccount.userId,
				accountId: res.data.eduWxAccount.accountId, // 微信用户需要这个ID做校验
				isLogin: true
			}
			
			if(info.userInfo.nickName) {
				userData.userName = info.userInfo.nickName
			}else{
				userData.userName = res.data.eduWxAccount.nickName
			}
			
			store.commit('setUserInfo', userData);
			if (type == "authorized") {
				userInfo.token = res.data.token;
				store.commit('setLoginPopupShow', false);
			} else {
				callback && callback();
			}
			uni.showToast({
				title: "登录成功"
			});
			
			// 登录成功后获取用户详情
			$http.get('/wx/auth/studentDetail/' + userData.userId).then(res => {
				//console.log(JSON.stringify(res))
				if(res.code === 200) {
					store.commit('setUserDetail', res.data);	
				}
			})
		} else {
			uni.showToast({
				title: "登录失败"
			});
		}
		
	}, err => {
		loginStart = true;
	});
}


//判断是否登录（所有端）
function judgeLogin(callback, storeUserInfo, type = "judge") {
	if (store.state.chatScenesInfo.scene == 1154) {
		uni.showToast({
			title: '请前往小程序使用完整服务',
			icon: "none"
		});
	} else {
		//let storeUserInfo = store.state.userInfo;
		//if (!storeUserInfo.token) { // nvue页面读取不到vuex里面数据，将取缓存
		//	storeUserInfo = uni.getStorageSync("userInfo");
		//}
		
		if (type != "force" && storeUserInfo && storeUserInfo.token) {
			callback();
		} else if (storeUserInfo && storeUserInfo.token && !storeUserInfo.phone) {
			if (type == "force") {
				uni.navigateTo({
					url: '/subpages/user/bindPhone'
				});
			} else {
				uni.showModal({
					title: "提示",
					content: "您还未绑定手机号，请先绑定~",
					confirmText: "去绑定",
					cancelText: "再逛会",
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/subpages/user/bindPhone'
							});
						}
					}
				});
			}
		} else {
			// #ifdef MP
			uni.showModal({
				title: "登录提示",
				content: "需要登录后才能操作",
				confirmText: "去登录",
				cancelText: "再逛会",
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: "/subpages/user/loginChange"
						});
					}
				}
			});
			// onLogin(type, callback);
			// #endif
			// #ifdef APP-PLUS
			uni.showModal({
				title: "登录提示",
				content: "此时此刻需要您登录喔~",
				confirmText: "去登录",
				cancelText: "再逛会",
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: "/subpages/user/login"
						});
					}
				}
			});
			// #endif
			// #ifdef H5
			h5Login(type, () => {
				callback();
			});
			// #endif
		}
	}
}

function reLoginData(storeUserInfo) {
	
}

export {
	onLogin,
	getUserInfo,
	judgeLogin,
	login,
	getUserProfile
}
